package org.csu.mybigpro.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class VisualSceneService {

    @Value("${stability.api.key}")
    private String apiKey;

    @Value("${stability.api.url}")
    private String apiUrl;

    @Autowired
    private RestTemplate restTemplate; // 复用您已配置好的RestTemplate

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 根据文本描述生成场景图片的Base64编码
     * @param description 场景描述，例如 "A vibrant, lush prehistoric jungle with volcanoes in the background"
     * @return 返回第一张图片的Base64编码字符串
     */
    public String generateScene(String description) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("Authorization", "Bearer " + apiKey);

        // 构建请求体，可以调整参数以获得不同风格的图片
        Map<String, Object> textPrompt = Map.of("text", description, "weight", 1);
        Map<String, Object> requestBody = Map.of(
                "text_prompts", List.of(textPrompt),
                "cfg_scale", 7,
                "height", 512,
                "width", 1024, // 生成适合作为背景的宽屏图片
                "samples", 1,
                "steps", 30,
                "style_preset", "photographic" // 使用照片风格，效果更逼真
        );

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        // 发起请求
        ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            JsonNode root = objectMapper.readTree(response.getBody());
            // 提取返回的base64图片数据
            return root.path("artifacts").path(0).path("base64").asText();
        } else {
            throw new RuntimeException("Failed to generate image from Stability AI: " + response.getBody());
        }
    }
}